package com.sea.product.controller;


import com.codecrane.core.controller.UploaderController;
import com.codecrane.core.power.service.DictDetailService;
import com.codecrane.core.util.DateUtils;
import com.codecrane.core.util.ExcelUtil;
import com.codecrane.core.web.Ajax;
import com.codecrane.core.web.AjaxReturn;
import com.codecrane.core.web.AjaxTableReturn;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.sea.product.entity.Category;
import com.sea.product.entity.Product;
import com.sea.product.service.CategoryService;
import com.sea.product.service.ProductService;
import org.apache.poi.hssf.usermodel.HSSFCellStyle;
import org.apache.poi.hssf.usermodel.HSSFDataFormat;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.jws.WebParam;
import javax.servlet.http.HttpServletResponse;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.util.Date;
import java.util.List;

@Controller
@RequestMapping(value = "/sea/product/product")
public class ProductController {

    @Autowired
    private ProductService productService;
    @Autowired
    private CategoryService categoryService;
    @Autowired
    private DictDetailService dictDetailService;

    @RequestMapping("/import")
    @ResponseBody
    public AjaxReturn importClubDo(Model model, MultipartFile file) {
        AjaxReturn result = Ajax.fail().setMsg("保存失败！");
        try {
            if (null == file || file.isEmpty()) {

                return result.setMsg("请上传文件！！！");
            } else {
                String fileName = file.getOriginalFilename();
                if (!(fileName.contains(".xls"))) {
                    return result.setMsg("只能上传excel文件！！！");
                }
                productService.importSku(file.getInputStream(), fileName);
                result.setOk(true);
                result.setMsg("上传成功！！");
            }
        }catch (Exception e) {
            e.printStackTrace();
            result.setMsg(e.getMessage());
            return result;
        }
        return result;
    }

    @RequestMapping("/importAdd")
    @ResponseBody
    public AjaxReturn importAdd(Model model, MultipartFile file) {
        AjaxReturn result = Ajax.fail().setMsg("保存失败！");
        try {
            if (null == file || file.isEmpty()) {
                return result.setMsg("请上传文件！！！");
            } else {
                String fileName = file.getOriginalFilename();
                if (!(fileName.contains(".xls"))) {
                    return result.setMsg("只能上传excel文件！！！");
                }
                productService.importAddSku(file.getInputStream(), fileName);
                result.setOk(true);
                result.setMsg("上传成功！！");
            }
        }catch (Exception e) {
            e.printStackTrace();
            result.setMsg(e.getMessage());
            return result;
        }
        return result;
    }


    /**
     * 管理主页面
     * @param model
     * @return
     */
    @RequestMapping("/main")
    public String main(Model model) {
        getModel(model);
        return "/sea/product/product/main";
    }
    /**
     * 新增页面
     *
     * @param model
     * @return
     */
    @RequestMapping("/addPage")
    public String addPage(Model model) {
        getModel(model);
        return "/sea/product/product/add";
    }
    /**
     * 新增页面
     *
     * @param model
     * @return
     */
    @RequestMapping("/editPage")
    public String editPage(Model model,@RequestParam("id")Integer id) {
        getModel(model);
        model.addAttribute("product",productService.findById(id));
        return "/sea/product/product/edit";
    }

     void getModel(Model model){
         model.addAttribute("category",categoryService.findCategory());
         model.addAttribute("color", dictDetailService.findByTypeCode("product_color", null));
         model.addAttribute("property", dictDetailService.findByTypeCode("product_property", null));
         model.addAttribute("size", dictDetailService.findByTypeCode("product_size", null));
         model.addAttribute("unit", dictDetailService.findByTypeCode("product_unit", null));
    }
    /**
     * 分页条件查询
     *
     * @param pagesize
     * @param start
     * @return
     */
    @ResponseBody
    @RequestMapping("/findByCnd")
    public AjaxTableReturn findByCnd(@RequestParam(value = "limit", defaultValue = "10") int pagesize,
                                     @RequestParam(value = "offset", defaultValue = "0") int start,
                                     Product product
                                     ) {
        start = start > 0 ? start / pagesize + 1 : 1;
        PageHelper.startPage(start, pagesize);
        List<Product> list = productService.findByCnd(product);
        PageInfo<Product> page = new PageInfo<>(list);
        return Ajax.tableDataOk(page.getTotal(), page.getList());
    }


    /**
     * 保存
     * @param product
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/save", method = RequestMethod.POST)
    public AjaxReturn save(Product product) {
        AjaxReturn result = Ajax.fail().setMsg("保存失败！");
        try{
            if (null != product && productService.save(product) > 0) {
                result.setOk(true).setMsg("保存成功！");
            }
        }catch (DuplicateKeyException e){
            result.setMsg("当前SKU不能重复!");
            return result;
        }catch (RuntimeException e){
            e.printStackTrace();
            result.setMsg(e.getMessage());
            return result;
        }catch (Exception e){
            e.printStackTrace();
            result.setMsg("系统异常,请联系管理员!");
            return result;
        }
        return result;
    }
    /**
     * 更新
     * @param product
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/usave", method = RequestMethod.POST)
    public AjaxReturn usave(Product product) {
        AjaxReturn result = Ajax.fail().setMsg("保存失败！");
        try{
            if (null != product && productService.usave(product) > 0) {
                result.setOk(true).setMsg("保存成功！");
            }
        }catch (RuntimeException e){
            e.printStackTrace();
            result.setMsg(e.getMessage());
            return result;
        }catch (Exception e){
            e.printStackTrace();
            result.setMsg("系统异常,请联系管理员!");
            return result;
        }
        return result;
    }
    /**
     * 根据SKU查找指定
     * @param sku
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/findBySku", method = RequestMethod.POST)
    public AjaxReturn findBySku(String sku) {
        AjaxReturn result = Ajax.fail().setMsg("查询失败！");
        try{
            Product product = productService.findBySku(sku);
            if (product != null) {
                result.setData(product);
                result.setOk(true).setMsg("保存成功！");
            }
        }catch (Exception e){
            e.printStackTrace();
            result.setMsg("系统异常,请联系管理员!");
            return result;
        }
        return result;
    }
    /**
     * 删除
     * @param id
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/delete", method = RequestMethod.POST)
    public AjaxReturn delete(Integer id) {
        AjaxReturn result = Ajax.fail().setMsg("删除失败！");
        try{
            if (null != id && productService.delete(id) > 0) {
                result.setOk(true).setMsg("删除成功！");
            }
        }catch (Exception e){
            e.printStackTrace();
            result.setMsg("系统异常,请联系管理员!");
            return result;
        }
        return result;
    }



    @RequestMapping("/importImg")
    @ResponseBody
    public AjaxReturn importClubDo( MultipartFile file) {
        AjaxReturn result = Ajax.fail().setMsg("上传失败！");
        try {
            if (null == file || file.isEmpty()) {
                return result.setMsg("请上传文件！！！");
            } else {
                UploaderController upload=new UploaderController();
                AjaxReturn ajaxReturn = upload.uploadFile(file, null);
                String string = ajaxReturn.getData().toString();
                ajaxReturn.setData(string);
                return ajaxReturn;
            }
        } catch (Exception e) {
            e.printStackTrace();
            result.setMsg(e.getMessage());
            return result;
        }
    }

    @RequestMapping(value = "/export", method = RequestMethod.GET)
    @ResponseBody
    public void export(HttpServletResponse response, Product product) {


        List<Product> list = productService.findByCnd(product);
        String[] title = {"SKU", "属性","产品名称","颜色","大类","中类","小类","尺码","尺码(CM)","尺码(INCH)",
                "单品毛重KG(产品重量+内盒)","单品净重KG(不含包装)","装箱量", "内含件数","外箱整重(KG)", "外箱长(CM)",
                "外箱宽(CM)", "外箱高(CM)", "外箱体积(m³)","产品体积(m³)","产品长(CM)", "产品宽(CM)","产品高(CM)",
                "单位","HS CODE","报关名称","UPC","生产周期","门幅","材质","英文品名","成分","创建时间","修改时间"};
        String fileName = "商品信息" + DateUtils.dateToString(new Date(), "yyyyMMdd") + ".xls";
        String sheetName = "商品信息";

        HSSFWorkbook wb = new HSSFWorkbook();
        Sheet sheet = wb.createSheet(sheetName);

        // 创建标题行
        Row titleRow = sheet.createRow(0);
        for (int i = 0; i < title.length; i++) {
            Cell cell = titleRow.createCell(i);
            cell.setCellValue(title[i]);
        }

        // 创建一个文本格式的单元格样式，用于避免科学计数法
        HSSFCellStyle textStyle = wb.createCellStyle();
        HSSFDataFormat format = wb.createDataFormat();
        textStyle.setDataFormat(format.getFormat("@"));

        // 填充数据行
        for (int i = 0; i < list.size(); i++) {
            Product obj = list.get(i);
            Row row = sheet.createRow(i + 1);

            row.createCell(0).setCellValue(obj.getProductSku());
            row.createCell(1).setCellValue(obj.getProductPropertyName());
            row.createCell(2).setCellValue(obj.getProductName());
            row.createCell(3).setCellValue(obj.getProductColorName());
            row.createCell(4).setCellValue(obj.getProductBigClassName());
            row.createCell(5).setCellValue(obj.getProductMidClassName());
            row.createCell(6).setCellValue(obj.getProductClassName());
            row.createCell(7).setCellValue(obj.getProductSizeName());
            row.createCell(8).setCellValue(obj.getProductCm());
            row.createCell(9).setCellValue(obj.getProductInch());
            row.createCell(10).setCellValue(obj.getProductGrossWeight());
            row.createCell(11).setCellValue(obj.getProductWeight());
            row.createCell(12).setCellValue(obj.getProductPackageNumber());
            row.createCell(13).setCellValue(obj.getProductContainCount());
            row.createCell(14).setCellValue(obj.getProductOutBoxWeight());
            row.createCell(15).setCellValue(obj.getProductOutBoxLength());
            row.createCell(16).setCellValue(obj.getProductOutBoxWidth());
            row.createCell(17).setCellValue(obj.getProductOutBoxHeight());
            row.createCell(18).setCellValue(obj.getProductOutBoxVolume());
            row.createCell(19).setCellValue(obj.getProductVolume());
            row.createCell(20).setCellValue(obj.getProductLength());
            row.createCell(21).setCellValue(obj.getProductWidth());
            row.createCell(22).setCellValue(obj.getProductHeight());
            row.createCell(23).setCellValue(obj.getProductUnit());
            row.createCell(24).setCellValue(obj.getProductCode());
            row.createCell(25).setCellValue(obj.getProductDeclarationName());

            // 设置UPC列为文本格式，避免科学计数法
            Cell upcCell = row.createCell(26);
            upcCell.setCellValue(obj.getProductUpc());
            upcCell.setCellStyle(textStyle);

            row.createCell(27).setCellValue((null==obj.getProductDay()?0+"":obj.getProductDay()+""));
            row.createCell(28).setCellValue(obj.getProductFabric());
            row.createCell(29).setCellValue(obj.getProductMaterial());
            row.createCell(30).setCellValue(obj.getProductEnName());
            row.createCell(31).setCellValue(obj.getProductComposition());
            row.createCell(32).setCellValue(obj.getCreateTime());
            row.createCell(33).setCellValue(obj.getModifyTime());
        }

        // 响应到客户端
        try {
            this.setResponseHeader(response, fileName);
            OutputStream os = response.getOutputStream();
            wb.write(os);
            os.flush();
            os.close();
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    //发送响应流方法
    public void setResponseHeader(HttpServletResponse response, String fileName) {
        try {
            try {
                fileName = new String(fileName.getBytes(), "ISO8859-1");
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
            response.setContentType("application/octet-stream;charset=ISO8859-1");
            response.setHeader("Content-Disposition", "attachment;filename=" + fileName);
            response.addHeader("Pargam", "no-cache");
            response.addHeader("Cache-Control", "no-cache");
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }
}
